#include "core/Server.hpp"
#include "core/protocol_handler.hpp"
#include "utils/logger.hpp"

int main(int /*argc*/, char** /*argv*/) {
    // 初始化日志系统
    Logger::init("logs/server.log");

    // 初始打印进程pid
    Logger::info("Server started, pid: {}", getpid());

    try {
        // 初始化事件循环
        EventLoop eventLoop(64);

        // 注册信号处理器
        SignalHandler signal(eventLoop);

        // 注册 SIGINT 处理函数
        signal.registerSignal(SIGINT, [&](int signum) {
            Logger::info("Received SIGINT, stopping event loop... signal: {}", signum);
            eventLoop.stop();
        });

        // 注册 SIGTERM 处理函数
        signal.registerSignal(SIGTERM, [&](int signum) {
            Logger::info("Received SIGTERM, stopping event loop... signal: {}", signum);
            eventLoop.stop();
        });

        // 初始化server
        Server server(eventLoop, "0.0.0.0", 8888);

        // 设置协议处理器为 WebSocketHandler
        auto protocolHandler = std::make_unique<WebSocketHandler>();
        server.setProtocolHandler(std::move(protocolHandler));

        // 设置连接回调
        server.setConnectionCallback([](const TcpConnectionPtr& conn) {
            if (conn->connected()) {
                Logger::info("New client connected: {}", conn->getPeerAddress().toIpPort());
            }
        });

        // 启动事件循环
        Logger::info("Server started");

        // 执行主循环
        eventLoop.run();

        // 打印退出信息
        Logger::info("Server stopped");
    } catch (const std::exception& e) {
        Logger::critical("Fatal error: {}", e.what());
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}